package org.demo.jwt.biz;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JOSEException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.text.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * JWT令牌管理Controller
 * Created by macro on 2020/6/22.
 */
@Api(tags = "JwtTokenController", description = "JWT令牌管理")
@Controller
@RequestMapping("/token")
public class JwtTokenController {

    @Autowired
    private JwtTokenService jwtTokenService;

    /**
     *
     * @param forSecure 用作签名加密的任意值
     * @return
     */
    @ApiOperation("使用对称加密（HMAC）算法生成token")
    @RequestMapping(value = "/hmac/generate", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult generateTokenByHMAC(@RequestParam String forSecure) {
        String message ;
        try {
            String verifySecure = SecureUtil.md5(forSecure);
            PayloadDto payloadDto = jwtTokenService.getDefaultPayloadDto();
            String token = jwtTokenService.generateTokenByHMAC(JSONUtil.toJsonStr(payloadDto), verifySecure);
            return CommonResult.success(token).setVerifySecure(verifySecure);
        } catch (JOSEException e) {
            message =  e.getMessage();
            e.printStackTrace();
        }
        return CommonResult.failed(message);
    }

    /**
     *
     * @param token 获取的token
     * @param verifySecure 同步返回的随机签名
     * @return
     */
    @ApiOperation("使用对称加密（HMAC）算法验证token")
    @RequestMapping(value = "/hmac/verify", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult verifyTokenByHMAC(@RequestParam String token,@RequestParam String verifySecure) {
        String message ;
        try {
            PayloadDto payloadDto  = jwtTokenService.verifyTokenByHMAC(token, verifySecure);
            return CommonResult.success(payloadDto);
        } catch (ParseException | JOSEException e) {
            message =  e.getMessage();
            e.printStackTrace();
        }
        return CommonResult.failed(message);

    }
}